import serial #导入模块
import threading
import serial.tools.list_ports
import time
from PyQt5.QtWidgets import QMessageBox


Data=""  #读取的数据
BOOL=True
SER = None
SHELLID = ""
ENDING = ""
ENDINGERROR = ""
ISWAIT = False




class Uart():
    def __init__(self, instance):
        self.myUi = instance
    #获取串口
    def GetPortList(self):
        return list(serial.tools.list_ports.comports())
    #读数代码本体实现
    def ReadData(self):
        global STRGLO,BOOL,SER
        # 循环接收数据，此为死循环，可用线程实现
        while BOOL:
            try:
             if SER.in_waiting:
                one = SER.read(SER.in_waiting).decode("gbk")
                global Data
                Data +=one
                # print(one)
                self.FindOneFrame()
            except Exception as e:
                print("read :异常", e)
                self.DColsePort()
                self.myUi.emit("showTipClose","设备拔出" )

    #打开串口
    # 端口，GNU / Linux上的/ dev / ttyUSB0 等 或 Windows上的 COM3 等
    # 波特率，标准值之一：50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,19200,38400,57600,115200
    # 超时设置,None：永远等待操作，0为立即返回请求结果，其他值为等待超时时间(单位为秒）
    def DOpenPort(self,portx,bps,timeout):
        global BOOL, SER
        BOOL = True
        ret=False
        try:
            # 打开串口，并得到串口对象
            SER = serial.Serial(portx, bps, timeout=timeout)
            #判断是否打开成功
            if(SER.is_open):
               ret=True
               threading.Thread(target=self.ReadData).start()
        except Exception as e:
            print("---异常---：", e)
        return ret

    #关闭串口
    def DColsePort(self):
        global BOOL,SER
        BOOL=False
        if SER != None:
          SER.close()
    def isNotOpen(self):
        if SER !=None and BOOL:
            return  False
        return  True
    #写数据
    def DWritePort(self,text):
        global SER
        try:
            text = text+"\n"
            print("发送:"+(text))
            result = SER.write(text.encode("gbk"))
        except Exception as e:
            print("---异常---：", e)
        return result

    def sendShell(self,shellID,end,endError,data):
        global SHELLID,ENDING,ENDINGERROR,ISWAIT
        try:
            if ISWAIT:
             self.myUi.emit("showTip", "正在进行其他操作请稍后")
             return
            SHELLID = shellID
            ENDINGERROR = endError
            ENDING = end
            self.DWritePort(data)
            if ENDING == "NOHAVE":
                ISWAIT = True
                t = threading.Thread(target=self.waitThread)
                t.start()
                #t.join()
        except Exception as e:
          print("---异常---：", e)

    def waitThread(self):
        global ISWAIT
        time.sleep(1)
        self.myUi.emit(SHELLID, Data)
        ISWAIT = False

    #找到一个包
    def FindOneFrame(self):
       global Data
       if ENDING!="":
           if ENDING == "NOHAVE":
               return
           index = Data.find(ENDING)
           if index > 0:
               if "Test" in SHELLID:
                   Data = ENDING
               self.myUi.emit(SHELLID, Data)
               Data = ""
               return
           elif ENDINGERROR!="":
               index = Data.find(ENDINGERROR)
               if index > 0:
                   if "Test" in SHELLID:
                       Data = ENDINGERROR
                   self.myUi.emit(SHELLID, Data)
                   Data = ""
                   return

       name = Data.find("login")
       if name > 0 :
           self.sendShell("","","","root")
           Data = ""
       word = Data.find("Password")
       if word > 0:
           self.sendShell("", "","", "dtu")
           Data = ""












